#include "serial_rx_thread.h"

Serial_Rx_Thread::Serial_Rx_Thread(Serial_Port* sp)
{
    stop_flag = true;
    //(void)sp;
    this->serial_port = sp;

    connect(this->serial_port,SIGNAL(read_serial_signals()),this,SLOT(slot_serial_port_rx_thread()));
}

Serial_Rx_Thread::~Serial_Rx_Thread()
{

}




void Serial_Rx_Thread::serial_port_data_process(char *p_data,unsigned int data_len)
{
    TYP_UN_COMMUNICATE_BUFF data_recv;
    unsigned char unpackage_data[256];
    unsigned char unpackage_len;

    memcpy(&data_recv.databuff,p_data,data_len);

    if(My_Protocol::check_crc(&data_recv))        //CRC 检验正确
    {
        switch(data_recv.Frame.cmd)
        {
            case CMD_GET_SYS_CONFIG:   //获取sys_config的信息
                //qDebug() << "CMD_GET_SYS_CONFIG";
                unpackage_len = My_Protocol::protocol_data_unpackage(&data_recv,unpackage_data);
                emit signal_get_sys_config(&unpackage_data[1],unpackage_len-1);
            break;

            case CMD_SET_SYS_CONFIG:    //设置sys_config的信息
                //qDebug() << "CMD_SET_SYS_CONFIG";
                unpackage_len = My_Protocol::protocol_data_unpackage(&data_recv,unpackage_data);
                emit signal_set_sys_config(&unpackage_data[1],unpackage_len-1);
            break;

            case CMD_GET_DEV_INFO:    //获取从机设备节点
                //qDebug() << "CMD_GET_DEV_INFO";
                unpackage_len = My_Protocol::protocol_data_unpackage(&data_recv,unpackage_data);
                emit signal_get_dev_info(&unpackage_data[1],unpackage_len-1);
            break;

            case CMD_MASTER_CTRL_SLAVE:
                unpackage_len = My_Protocol::protocol_data_unpackage(&data_recv,unpackage_data);
                emit signal_slave_notify(&unpackage_data[1],unpackage_len-1);
            break;

            default:
            break;
        }
    }
    else    // CRC 校验失败
    {

    }
}

void Serial_Rx_Thread::slot_serial_port_rx_thread()
{
    //qDebug() << "serial_port_rx_thread";
    {
        QMutexLocker locker(&stop_mutex);
        stop_flag = false;
    }

    unsigned int data_len = 0;
    char data_buff[1024];

    while(1)
    {
        {
            QMutexLocker locker(&stop_mutex);
            if(stop_flag)
            return;
        }
        memset(data_buff,0x00,sizeof(data_buff));

        data_len = serial_port->serial_port_rx_queue->circlebuff_read_packet_data(data_buff);

        if(data_len > 0)
        {
            serial_port_data_process(data_buff,data_len);
        }
        else {
            stop_thread();
        }
    }
}

void Serial_Rx_Thread::stop_thread()
{
    {
        QMutexLocker locker(&stop_mutex);
        stop_flag = true;
    }
}
